package com.pcitc.smcc.vulnerability.common.handler;

import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.pcitc.smcc.vulnerability.entity.ResultWrapper;

import lombok.extern.slf4j.Slf4j;

/**
 * 全局异常处理
 * @author:张三石
 * @since:2020年3月30日 下午4:19:45
 */

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

	/**
	 * 校验错误拦截处理
	 * @param exception BindException类型异常
	 * @return Object 包装处理结果
	 */
	@ExceptionHandler(BindException.class)
	public Object handleMethodArgumentNotValidException(final BindException exception) {
		StringBuilder sb = new StringBuilder();
		BindingResult bindingResult = exception.getBindingResult();
		bindingResult.getAllErrors().forEach(error -> {
			sb.append(error.getDefaultMessage()).append("<br/> ");
		});
		return new ResultWrapper<>(800100, sb.toString(), exception.getMessage());
	}

	/**
	 * 参数类型转换错误
	 * @param exception HttpMessageConversionException类型异常
	 * @return Object 包装处理结果
	 */
	@ExceptionHandler(HttpMessageConversionException.class)
	public Object handleHttpMessageConversionException(HttpMessageConversionException exception) {
		String localizedMessage = exception.getCause().getLocalizedMessage();
		return new ResultWrapper<>(800200, localizedMessage, exception.getMessage());
	}

	/**
	 * 运行时异常处理
	 * @param exception RuntimeException类型异常
	 * @return Object 包装处理结果
	 */
	@ExceptionHandler(RuntimeException.class)
	public Object handleRuntimeException(final RuntimeException exception) {
		log.error(exception.getMessage(), exception);
		return new ResultWrapper<>(600, "运行过程中出现异常", exception.getMessage());
	}

	/**
	 * 系统异常处理
	 * @param exception Exception类型异常
	 * @return Object 包装处理结果
	 */
	@ExceptionHandler(Exception.class)
	public Object handleSystemException(final Exception exception) {
		log.error(exception.getMessage(), exception);
		return new ResultWrapper<>(700, "系统出错", exception.getMessage());
	}

}